package com.hbnu.exercise.net;

import java.io.*;
import java.net.Socket;


public class TcpServerThreadDemo06 implements Runnable
{
    private Socket socket;
    private static int count = 1;

    public TcpServerThreadDemo06(Socket socket)
    {
        this.socket = socket;
    }
    @Override
    public void run()
    {
        String ip = socket.getInetAddress().getHostAddress();
        File file = new File("D:\\" + ip + ".jpg");
        if (file.exists())
        {
            file = new File("D:\\" + ip + "(" + (count++) + ").jpg");
        }
        try
        {
            InputStream in = socket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = in.read(bytes)) != -1)
            {
                fileOutputStream.write(bytes, 0, length);
            }

            out.println("图片上传成功");

            fileOutputStream.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}